const player = document.querySelector('.player');
const videoElement = player.querySelector('.player__video');
const splashLayerElement = player.querySelector('.splash-layer');
const progressLine = player.querySelector('.player__controls > .progress');
const progressFill = progressLine.querySelector('.progress__filled');
const toogleBtn = player.querySelector('.player__controls > .player__button.toogle');
const volumeBtn = player.querySelector('.player__controls .player__sound-controller > .player__button');
const toastSliders = player.querySelectorAll('.player__controls > .add-controllers > .toast-slider');
const skipTimeBtns = player.querySelectorAll('.player__controls  .add-controllers > .player__button.skip-time');
let notifyStatusTimeout = 0;
let lastVolumeVal = 1;
let statusProgressTimeout = 0; 

function notifyStatusPlayer(nameStatus) {
    if (!['pause', 'start', 'rollfoward', 'rollback', 'mute', 'unmute']) return;

    if (notifyStatusTimeout) {
        clearTimeout(notifyStatusTimeout);
        splashLayerElement.querySelector(`.status.active`)?.classList.remove('active');
    }

    const statusElement = splashLayerElement.querySelector(`.status.${nameStatus}`);
    statusElement.classList.add('active');  
    notifyStatusTimeout = setTimeout(() => {
        statusElement.classList.remove('active');
    }, 1000);
}

function tooglePlayer() {
    const method = videoElement.paused ? 'play' : 'pause';
    notifyStatusPlayer(videoElement.paused ? 'start' : 'pause');
    const statusElInBtn = toogleBtn.querySelector('& > i');

    if (statusElInBtn.classList.contains('fa-play')) {
        statusElInBtn.classList.remove('fa-play');
        statusElInBtn.classList.add('fa-pause');
    } else {
        statusElInBtn.classList.add('fa-play');
        statusElInBtn.classList.remove('fa-pause');
    }

    videoElement[method]();
}

function skipHandler() {
    console.log('skip', this.dataset.skip);
    videoElement.currentTime += parseFloat(this.dataset.skip);
}

const setVolumeVideo = (value) => videoElement.volume = value; 

const setValueStatus = (status, targetEl, positiveIcon, negativeIcon) => {
    if (status === 'unmuted') {
        targetEl.classList.remove(negativeIcon);
        targetEl.classList.add(positiveIcon);
    } else if (status === 'muted') {
        targetEl.classList.remove(positiveIcon);
        targetEl.classList.add(negativeIcon);
    }
} 

function videoRangeHandler() {
    if (this.name === 'volume') {
        const btnStatus = this.parentNode.parentNode.querySelector('.player__button > i');
        
        if (this.value == 0) {
            setValueStatus('muted', btnStatus, 'fa-volume-up', 'fa-volume-off');
        } else if (this.value > 0 && videoElement.volume == 0) {
            setValueStatus('unmuted', btnStatus, 'fa-volume-up', 'fa-volume-off');
        }

        setVolumeVideo(this.value);
        return;
    }

    videoElement[this.name] = this.value;
}

function volumeVideoBtnHandler() {
    if (videoElement.muted) {
        videoElement.muted = false;
        setValueStatus('unmuted');
        return;
    }

    videoElement.muted = true;
    setValueStatus('muted');
}

function statusProgress(elProgress, percent) {
    if (statusProgressTimeout) clearTimeout(statusProgressTimeout);
    statusProgressTimeout = setTimeout(() => elProgress.style.flexBasis = `${percent}%`, 100);
}

function handleProgress(elProgress) {
    return () => {
        const percent = (videoElement.currentTime / videoElement.duration) * 100;

        console.log('handleProgress percent', percent);
        statusProgress(elProgress, percent);
    }
}

function scrubHandler(elProgress, elVideo) {
    let mouseDown = false;
    let changeTimeout = 0;

    return {
        setMouseStatus: (status) => mouseDown = status,
        scrubing: (e) => {
            const scrubTime = (e.offsetX / e.target.parentNode.offsetWidth) * elVideo.duration;
            const percent = (scrubTime / videoElement.duration) * 100;
            elVideo.currentTime = scrubTime;
        },
        mouseStatus: () => mouseDown
    }
}

toogleBtn.addEventListener('click', tooglePlayer);
splashLayerElement.addEventListener('click', tooglePlayer);
volumeBtn.addEventListener('click', volumeVideoBtnHandler);
toastSliders.forEach((el) => {
    el.querySelector('.slider-background input[type=range]')?.addEventListener('input', videoRangeHandler);
});
skipTimeBtns.forEach((el) => el.addEventListener('click', skipHandler));
videoElement.addEventListener('timeupdate', handleProgress(progressFill));

const scrub = scrubHandler(progressFill, videoElement);

progressLine.addEventListener('click', scrub.scrubing);
progressLine.addEventListener('drag', (e) => e.preventDefault());
progressLine.addEventListener('mousemove', (e) => scrub.mouseStatus() && scrub.scrubing(e));
progressLine.addEventListener('mousedown', () => scrub.setMouseStatus(true));
progressLine.addEventListener('mouseup', () => scrub.setMouseStatus(false));
progressLine.addEventListener('mouseout', () => scrub.setMouseStatus(false));